package com.chenwc.netty.tcp.enums;

import com.chenwc.netty.tcp.coder.Message;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 数据类型枚举类
 */
public enum MessageEnum {
    CONNECT(1, "心跳消息"),
    STATE(2, "设备状态"),
    COMMAND(3, "下发命令"),
    UNKNOWN(0, "未知状态");

    public final Integer type;
    public final String content;

    MessageEnum(Integer type, String content) {
        this.type = type;
        this.content = content;
    }

    /**
     * 根据type获取消息类型
     * @param type type
     * @return MessageEnum
     */
    public static MessageEnum getStructureEnum(Integer type) {
        for (MessageEnum msg : MessageEnum.values()){
            if (Objects.equals(type, msg.getType())){
                return msg;
            }
        }
        return MessageEnum.UNKNOWN;
    }

    /**
     * 根据msg获取消息类型
     * @param msg Message
     * @return MessageEnum
     */
    public static MessageEnum getStructureEnum(Message msg) {
        MessageEnum type = Optional.ofNullable(msg)
                .map(Message::getMsgType)
                .orElse(MessageEnum.UNKNOWN);
        if (type.getType() != 0) {
            List<MessageEnum> objectEnums = Arrays.stream(MessageEnum.values())
                    .filter((item) -> Objects.equals(item.getType(), type.getType()))
                    .distinct()
                    .collect(Collectors.toList());
            if (objectEnums.size() > 0) {
                return objectEnums.get(0);
            }
        }
        return null;
    }

    public Integer getType() {
        return type;
    }

    public String getContent() {
        return content;
    }
}